import { KeyboardInput } from '../../input/keyboard-input';
import { IWorld } from '../common/world.interface';
import { EventComponent } from '../components/event.component';
import { System } from './system';

export interface IInputConfig {
  eventBindings: {
    [code: string]: EventComponent;
  };
}

export class InputDetectionSystem extends System {
  #rawInput = new KeyboardInput();

  constructor(private readonly config: IInputConfig) {
    super();
  }

  onStart(world: IWorld): void {
    this.#rawInput.start();
  }

  onUpdate(world: IWorld, dt: number) {
    const { eventBindings } = this.config;

    Object.keys(eventBindings).forEach((code) => {
      if (this.#rawInput.checkIfKeyIsDown(code)) {
        world.pushEvent(EventComponent, eventBindings[code]);
      }
    });
  }

  onFinish() {
    this.#rawInput.finish();
  }
}
